import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class RemoveKdigits {

    public static void main(String[] args) {
        RemoveKdigits removeKdigits = new RemoveKdigits();
        String s = "9";
        System.out.println(removeKdigits.removeKdigits(s, 1));
    }

    String ans = "";

    public String removeKdigits1(String num, int k) {
        dfs(num, 0, new ArrayList<>(), k);
        ans = ans.equals("") ? "0" : ans.replaceAll("^(0+)", "");
        return ans.equals("") ? "0" : ans;
    }

    public void dfs(String num, int i, List<Integer> list, int k) {
        if (i == num.length() || list.size() == k) {
            if (list.size() == k) {
                Collections.sort(list, (a, b) -> b - a);
                StringBuilder stringBuilder = new StringBuilder(num);
                for (int j = 0; j < list.size(); j++) {
                    stringBuilder.deleteCharAt(list.get(j));
                }
                if (ans.length() == 0) {
                    ans = stringBuilder.toString();
                } else {
                    ans = ans.compareTo(stringBuilder.toString()) > 0 ? stringBuilder.toString() : ans;
                }
            }
            return;
        }
        dfs(num, i + 1, list, k);
        list.add(i);
        dfs(num, i + 1, list, k);
        list.remove(list.indexOf(i));
    }

    public String removeKdigits(String num, int k) {
        if (k == num.length()) return "0";
        Stack<Character> stack = new Stack<>();
        int count = 0;
        int i = 0;
        for (; i < num.length(); i++) {
            while (!stack.isEmpty() && stack.peek() > num.charAt(i) && k > count) {
                stack.pop();
                ++count;
            }
            stack.push(num.charAt(i));
            if (count == k) break;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int j = 0; j < stack.size(); j++) {
            stringBuilder.append(stack.get(j));
        }
        if (i != num.length()) {
            stringBuilder.append(num.substring(i + 1, num.length()));
        }
        ans = stringBuilder.toString();
        if (count < k) {
            ans = ans.substring(0, ans.length() - (k - count));
        }
        ans = ans.equals("") ? "0" : ans.replaceAll("^(0+)", "");
        return ans.equals("") ? "0" : ans;
    }
}
